package com.ms.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密算法
 * @author ms
 * @since 2018-7-25
 */
public class AesUtil {

	// 转化十六进制的字符串--加密需要
	public static String bytesToStr(byte[] by) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < by.length; i++) {
			String tmp = Integer.toHexString(by[i] & 0xFF);
			if (tmp.length() == 1)
				sb.append("0");
			sb.append(tmp);
		}
		return sb.toString();
	}

	// 十六进制的字符串转化为字节数组--解密需要
	public static byte[] strtoBytes(String str) {
		if (str == null || str.trim().equals("")) {
			return new byte[0];
		}
		byte[] bytes = new byte[str.length() / 2];
		for (int i = 0; i < str.length() / 2; i++) {
			String subStr = str.substring(i * 2, i * 2 + 2);
			bytes[i] = (byte) Integer.parseInt(subStr, 16);
		}
		return bytes;
	}

	/**
	 * 
	 * @param opmode 1：加密；2：解密
	 * @param content 加密内容
	 * @param password 密钥
	 * @return
	 */
	public static byte[] aes(int opmode, byte[] content, String password) {
		try {
			Cipher des = Cipher.getInstance("AES");
			des.init(opmode, new SecretKeySpec(password.getBytes("UTF-8"), "AES"));
			return des.doFinal(content);
		} catch (Throwable ex) {
			return null;
		}
	}

	public static void main(String[] args) throws Exception {
		String con = "zhanghao1010";
		String s = bytesToStr(aes(1, con.getBytes("UTF-8"), "i2l87ZWgkxoghjvL"));
		System.out.println(s);
		System.out.println(new String(aes(2, strtoBytes(s), "i2l87ZWgkxoghjvL")));

	}


}
